//
//  JFBDropdownMenu.m
//  ios-supplier
//
//  Created by ccu on 15/8/26.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "JFBDropdownMenu.h"

@interface JFBDropdownMenu()

@property (nonatomic, weak) UIImageView *containerView;
@end

@implementation JFBDropdownMenu

- (UIImageView *)containerView
{
    if (!_containerView) {
        UIImageView *containerView = [[UIImageView alloc] init];
        containerView.userInteractionEnabled = YES;
        [self addSubview:containerView];
        self.containerView = containerView;
    }
    return _containerView;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

+ (instancetype)menu
{
    return [[self alloc] init];
}

- (void)setContent:(UIView *)content
{
    _content = content;
    content.x = 0;
    content.y = 0;
    
    self.content.layer.borderWidth = 1;
    self.content.layer.borderColor = [UIColor colorFromHexValue:0xf1f1f1].CGColor;
    
    self.containerView.height = CGRectGetMaxY(content.frame) + 5;
    self.containerView.width = CGRectGetMaxX(content.frame) + 10;
    
    [self.containerView addSubview:content];
}

- (void)setContentController:(UIViewController *)contentController
{
    _contentController = contentController;
    
    self.content = contentController.view;
}

- (void)showFrom:(UIView *)from
{

    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    
    [window addSubview:self];

    self.frame = window.bounds;

    CGRect newFrame = [from convertRect:from.bounds toView:window];

    self.containerView.centerX = CGRectGetMidX(newFrame);
    self.containerView.y = CGRectGetMaxY(newFrame);
}

- (void)dismiss
{
    [self removeFromSuperview];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self dismiss];
}
@end
